package cn.fql.org.service.impl;

import cn.fql.basic.service.impl.BaseServiceImpl;
import cn.fql.basic.util.PageList;
import cn.fql.org.domain.Department;
import cn.fql.org.mapper.DepartmentMapper;
import cn.fql.org.query.DepartmentQuery;
import cn.fql.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

   @Autowired
   private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        List<Department> departments = departmentMapper.loadAll();
        //把所有的部门查询出来后 撞到map里面 就是为了方便通过id找到部门对象
        Map<Long,Department> map = new HashMap<>();
        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        List<Department> deptTree = new ArrayList<>();
        //遍历所有的部门
        for (Department department : departments) {
            if(department.getParent_id() == null){
                //如果为空，那么进入的都是顶级部门  就添加到部门树
                deptTree.add(department);
            }else{
                //这里面就是有父级部门的
                Long parent_id = department.getParent_id();//找到他父级的部门
                //获取父级部门的对象
                Department parentDepartment = map.get(parent_id);
                if(parentDepartment != null){
                    //把自己的放到父级部门的children里面
                    parentDepartment.getChildren().add(department);
                }
            }
        }
        return deptTree;
    }
}
